<template>
  <div class="app-container">
    <el-table v-loading="loading" :data="questionnaireList.filter(item => item.publishStatus !== 0)" style="width: 100%">
  <el-table-column label="标题" align="center" prop="title">
    <template #default="{ row }">
      <span style="color: goldenrod; font-weight: bold;">{{ row.title }}</span>
    </template>
  </el-table-column>
  <el-table-column label="描述" align="center" prop="description" />

  <el-table-column label="图片" align="center" width="200">  
    <template slot-scope="scope">  
      <img :src="scope.row.picture" alt="图片" style="width: 100%; height: auto;">  
    </template>  
  </el-table-column> 

  <el-table-column align="center" label="开始时间" prop="startTime">
    <template slot-scope="scope">
      <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
    </template>
  </el-table-column>

  <el-table-column align="center" label="截至时间" prop="endTime">
    <template slot-scope="scope">
      <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
    </template>
  </el-table-column>

  <el-table-column align="center" label="剩余回答次数" prop="userLimit" />

  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
    <template slot-scope="scope">
      <el-button size="large" type="primary" plain icon="el-icon-info" @click="handleView(scope.row)" style="padding: 10px 10px; border-radius: 4px;">
        查看问卷
      </el-button>
    </template>
  </el-table-column>
</el-table>



      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="loadQuestionnaires"
      />

    <el-dialog title="选择参与方式" :visible.sync="authDialogVisible" width="400px" class="custom-dialog">
      <p>请选择参与问卷的方式：</p>
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="primary" @click="handleAuthChoice('real')">实名参与</el-button>
        <el-button type="info" @click="handleAuthChoice('anonymous')">匿名参与</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="questionnaireDetails.title" :visible.sync="viewDialogVisible" width="600px">
      <el-form :model="questionnaireData" label-width="120px" class="questionnaire-form">
        <div v-for="(question, index) in questionnaireDetails" :key="question.questionId" class="question-item">
          <el-form-item :label="'问题 ' + (index + 1)" class="question-form-item">
            <div class="question-text">{{ question.questionText }}</div>

            <!-- 单选 -->
            <div v-if="question.questionType === '0'">
              <el-radio-group v-model="questionnaireData[question.questionId]" class="option-group">
                <el-radio v-for="option in question.options" :key="option.optionId" :label="option.optionId">
                  {{ option.optionText }}
                </el-radio>
              </el-radio-group>
            </div>

            <!-- 多选 -->
            <div v-else-if="question.questionType === '1'">
              <el-checkbox-group v-model="questionnaireData[question.questionId]" class="option-group">
                <el-checkbox v-for="option in question.options" :key="option.optionId" :label="option.optionId">
                  {{ option.optionText }}
                </el-checkbox>
              </el-checkbox-group>
            </div>

            <!-- 文本输入 -->
            <div v-else-if="question.questionType === '2'">
              <el-input v-model="questionnaireData[question.questionId]" placeholder="请输入答案" />
            </div>
          </el-form-item>
        </div>

        <div align="center">
          <el-button type="primary" @click="handleSubmit" size="large">提交问卷</el-button>
        </div>
      </el-form>
    </el-dialog>
 
  </div>
</template>

<script>
import { getAllQuestionnaires,getQuestionnaireDetails,submitResponse,submitResponseBatch} from "@/api/questionnaire/questionnaire";
import axios from 'axios';
export default {
  name: "QuestionnaireView",
  dicts: ['question_type', 'publish_status','hdh_status'],
  data() {
    return {
      authDialogVisible: false, // 控制选择参与方式对话框
      viewDialogVisible: false,
      selectedAuthType: null,  
      questionnaireData: {},
      questionnaireDetails: [],
       // 遮罩层
       loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedZxhQuestion: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问卷信息表格数据
      questionnaireList: [],
      // 问题信息表格数据
      zxhQuestionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          description: null,
          startTime: null,
          endTime: null,

        },
       // 表单参数
       form: {},
    };
  },
  created() {
    this.loadQuestionnaires();
  },
  
  methods: {
    async loadQuestionnaires() {
      try {
        this.loading = true;
        // const response = await getAllQuestionnaires();
        getAllQuestionnaires(this.queryParams).then(response => {
        this.questionnaireList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
        //this.questionnaireList = response;
      } catch (error) {
        console.error("Error fetching questionnaires:", error);
      }
    },
   

    async handleView(row) {
      this.selectedQuestionnaire = row; // 保存当前选择的问卷信息
      this.authDialogVisible = true;   // 打开选择参与方式的小对话框
    },

    handleAuthChoice(authType) {
      this.selectedAuthType = authType; // 保存用户选择的参与方式
      this.authDialogVisible = false;  // 关闭选择对话框
      this.loadQuestionnaireDetails(); // 加载问卷详情
    },

    async loadQuestionnaireDetails() {
      const questionnaireId = this.selectedQuestionnaire.questionnaireId;
      try {
        const response = await getQuestionnaireDetails(questionnaireId);
        console.log('API Response:', response);

        if (Array.isArray(response)) {
          let questions = [];
          response.forEach(item => {
            let question = questions.find(q => q.questionId === item.questionId);
            if (!question) {
              question = {
                questionId: item.questionId,
                title: item.title,
                questionText: item.questionText,
                questionType: item.questionType,
                options: item.options || [],
                selectedOption: null, // 单选问题的默认值
                selectedOptions: []  // 多选问题的默认值
              };
              questions.push(question);
            }
            question.options.push({
              optionId: item.optionId,
              optionText: item.optionText
            });
          });

          this.questionnaireDetails = questions;

          // 初始化 questionnaireData[questionId] 为数组，确保多选时绑定正确
          this.questionnaireDetails.forEach(question => {
            if (question.questionType === '1') { // 多选题
              this.$set(this.questionnaireData, question.questionId, []); // 初始化为空数组
            }
          });

          this.viewDialogVisible = true;
        } else {
          this.$message.error("获取到的问卷详细信息格式不正确");
        }
      } catch (error) {
        console.error(error);
        this.$message.error("获取问卷详细信息失败: " + error.message);
      }
    },
    async handleSubmit() {
  // 判断当前时间是否超过问卷的截止时间
  const currentTime = new Date().getTime();
  const endTime = new Date(this.selectedQuestionnaire.endTime).getTime();
  if (currentTime > endTime) {
    this.$message.error("问卷已过期，不能提交");
    return; // 如果过期，阻止提交
  }

  // 构建提交数据，将每个问题封装成单独的对象
  const responses = this.questionnaireDetails.map((question) => {
    let selectedAnswer = null;

    // 单选题处理
    if (question.questionType === '0') {
      const selectedOptionId = this.questionnaireData[question.questionId];
      selectedAnswer = question.options
        .filter(option => option.optionId === selectedOptionId) // 找到选中的选项
        .map(option => ({
          optionId: option.optionId,
          optionText: option.optionText
        }))[0]; // 获取选中的选项 ID 和内容
    }

    // 多选题处理
    else if (question.questionType === '1') {
      selectedAnswer = question.options
        .filter(option => this.questionnaireData[question.questionId]?.includes(option.optionId)) // 找到选中的选项
        .map(option => ({
          optionId: option.optionId,
          optionText: option.optionText
        })); // 获取选中的选项 ID 和内容
    }

    // 填空题处理
    else if (question.questionType === '2') {
      selectedAnswer = this.questionnaireData[question.questionId]; // 文本答案
    }

    return {
      responseId: null, // 每个问题的回答记录ID，后端生成
      questionnaireId: this.selectedQuestionnaire.questionnaireId, // 问卷ID
      questionId: question.questionId, // 当前问题ID
      responseData: JSON.stringify(selectedAnswer), // 用户选择的选项内容，字符串化
      responseTime: new Date().toISOString(), // 提交时间
      isanonymous: this.selectedAuthType === 'anonymous' ? 0 : 1, // 是否匿名
    };
  });

  try {
    // 调用后端批量提交API
    await submitResponseBatch(responses);

    // 提交成功后减少剩余回答次数
    this.selectedQuestionnaire.userLimit -= 1;

    // 更新问卷列表
    const index = this.questionnaireList.findIndex(
      (item) => item.questionnaireId === this.selectedQuestionnaire.questionnaireId
    );
    if (index !== -1) {
      this.$set(this.questionnaireList, index, { ...this.selectedQuestionnaire });
    }

    this.$message.success("问卷提交成功");
    this.viewDialogVisible = false; // 关闭对话框
    this.questionnaireData = {}; // 清空回答数据
  } catch (error) {
    console.error(error);
    this.$message.error("问卷提交失败: " + error.message);
  }
},


  },
};
</script>

<style>
.custom-dialog .el-dialog__body {
  background-color:beige /* 设置整个对话框背景为淡黄色 */
}

.questionnaire-form {
  padding: 10px;
  background-color: rgb(225, 242, 255); /* 设置表单背景色为淡黄色 */
}

.question-item {
  margin-bottom: 10px; /* 缩小每个问题项之间的行距 */
  background-color: rgb(225, 244, 255); /* 设置每个问题项的背景色 */
  padding: 10px;
  border-radius: 4px;
}

.question-item:last-child {
  margin-bottom: 2px; /* 缩小最后一个问题和下一个问题之间的间距 */
}

.question-text {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 6px; /* 缩小问题文本与选项之间的间距 */
}

.option-group {
  display: flex;
  flex-direction: column;
}

.option-group .el-radio,
.option-group .el-checkbox {
  margin-bottom: 8px; /* 增加选项之间的间距 */
}

.text-area {
  width: 100%;
  margin-top: 6px; /* 调整文本框和选项之间的间距 */
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px;
}
.el-button {
  display: inline-block;
  visibility: visible;
  opacity: 1;
}
.custom-dialog {
  text-align: center;
}

.custom-dialog p {
  font-size: 16px;
  color: #333;
  margin-bottom: 20px;
}
</style>


